from smb.SMBConnection import SMBConnection
import os

# 配置网络共享路径和登录信息
server_ip = "192.168.1.101"  # 服务器IP
share_name = "d"  # 共享文件夹名称
username = "comiee"  # 登录用户名
password = "19980722"  # 登录密码
domain = ""  # 域（如果有的话）
remote_path = "/mei/小魅二代/source/data/sql_backup"  # 远程路径
local_path = "./sql_backup"  # 本地路径

# 连接到SMB服务器
conn = SMBConnection(username, password, "client_name", "server_name",
                     domain=domain, use_ntlm_v2=True, is_direct_tcp=True)
conn.connect(server_ip, 445)

# 获取远端目录下的文件列表
remote_files = conn.listPath(share_name, remote_path)
remote_file_names = [file.filename for file in remote_files if file.filename not in [".", ".."]]

# 获取本地目录下的文件列表
if not os.path.exists(local_path):
    os.makedirs(local_path)
local_files = os.listdir(local_path)

# 同步文件
for remote_file in remote_files:
    if remote_file.filename in [".", ".."]:
        continue  # 跳过当前目录和上级目录

    remote_file_path = os.path.join(remote_path, remote_file.filename)
    local_file_path = os.path.join(local_path, remote_file.filename)

    # 如果本地文件不存在或需要更新，则下载文件
    if not os.path.exists(local_file_path) or remote_file.file_size != os.path.getsize(local_file_path):
        with open(local_file_path, "wb") as f:
            conn.retrieveFile(share_name, remote_file_path, f)
        print(f"下载并覆盖文件: {remote_file.filename}")

# 删除本地多余的文件
for local_file in local_files:
    if local_file not in remote_file_names:
        os.remove(os.path.join(local_path, local_file))
        print(f"删除本地多余的文件: {local_file}")

# 关闭连接
conn.close()
